package practice.tmp;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Solution417 {
    public List<List<Integer>> pacificAtlantic(int[][] heights) {
        int m = heights.length;
        int n = heights[0].length;
        boolean[][] pac = new boolean[m][n];
        boolean[][] atl = new boolean[m][n];
        for (int i = 0; i < n; i++) {
            if (!pac[0][i]) {
                dfs(heights, 0, i, pac);
            }
            if (!atl[m - 1][i]) {
                dfs(heights, m - 1, i, atl);
            }
        }
        for (int i = 0; i < m; i++) {
            if (!pac[i][0]) {
                dfs(heights, i, 0, pac);
            }
            if (!atl[i][n - 1]) {
                dfs(heights, i, n - 1, atl);
            }
        }
        List<List<Integer>> res = new LinkedList<>();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (pac[i][j] && atl[i][j]) {
                    ArrayList<Integer> tmp = new ArrayList<>();
                    tmp.add(i);
                    tmp.add(j);
                    res.add(tmp);
                }
            }
        }
        return res;
    }

    public void dfs(int[][] heights, int i, int j, boolean[][] visited) {
        if (visited[i][j]) return;
        visited[i][j] = true;
        if (i - 1 >= 0 && heights[i - 1][j] >= heights[i][j]) dfs(heights, i - 1, j, visited);
        if (i + 1 < heights.length && heights[i + 1][j] >= heights[i][j]) dfs(heights, i + 1, j, visited);
        if (j - 1 >= 0 && heights[i][j - 1] >= heights[i][j]) dfs(heights, i, j - 1, visited);
        if (j + 1 < heights[0].length && heights[i][j + 1] >= heights[i][j]) dfs(heights, i, j + 1, visited);
    }
}
